package com.startx.core.netty.output.http;

import java.io.UnsupportedEncodingException;

import com.startx.core.system.constants.Headers;
import com.startx.core.tools.xml.XmlWriter;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * http短连接数据返回
 */
public class XmlOutput {

	/**
	 * 返回Object，默认转为json
	 * 
	 * @param ctx
	 * @param status
	 * @param result
	 * @throws UnsupportedEncodingException
	 */
	public static void object(ChannelHandlerContext ctx, HttpResponseStatus status, Object result)
			throws UnsupportedEncodingException {
		ByteBuf buffer = Unpooled.wrappedBuffer(XmlWriter.startXml().writeObject(result).endXml().getBytes("utf-8"));
		FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
		setPublicHeader(res);
		ChannelFuture f = ctx.channel().writeAndFlush(res);
		f.addListener(ChannelFutureListener.CLOSE);
	}

	/**
	 * 设置公共header
	 * @param res
	 */
	private static void setPublicHeader(FullHttpResponse res) {
		res.headers().add(Headers.getXmlHeader());
	}
}
